<template>
  <a-modal
    v-model:visible="visible"
    :title="submitType == 'add' ? '添加商品' : '编辑商品'"
    @cancel="close"
    zIndex="1000"
    width="600px"
  >
    <div class="content">
      <!-- 标题 -->
      <div class="title">
        <div class="lf">商品图片</div>
        <div class="rg">可拖拽商品图调整顺序</div>
      </div>

      <!-- 商品图片列表 -->
      <draggable
        v-if="detailInfo?.good_imgs?.length > 0"
        v-model="detailInfo.good_imgs"
        draggable=".productImg-item"
        class="productImg-list"
      >
        <template #item="{ element, index }">
          <div class="productImg-item">
            <img :src="element?.img" alt="" v-lazy="element?.img" />
          </div>
        </template>
      </draggable>
      <!-- 无商品图片 -->
      <a-empty :image="simpleImage" v-else />
      <div class="title">
        <div class="lf">商品原标题</div>
      </div>
      <div class="original_title">
        {{ detailInfo?.title }}
      </div>
      <div class="title">
        <div class="lf">商品短标题</div>
        <div class="rg">最多输入10个汉字</div>
      </div>
      <a-form style="margin-top: 10px" ref="formRef" :model="formState">
        <a-form-item
          name="sort_title"
          :rules="[{ required: true, message: '请输入商品短标题' }]"
        >
          <a-input
            placeholder="请输入商品短标题"
            v-model:value="formState.sort_title"
            show-count
            :maxlength="10"
            allowClear
          ></a-input>
        </a-form-item>
      </a-form>
      <div class="title">
        <div class="lf">
          <span style="margin-right: 5px"
            >每单赚<span style="color: red"
              >{{ detailInfo?.cos_fee_text }}
            </span></span
          ><span>售价<span></span>{{ detailInfo?.price_text }}</span>
        </div>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close">取消</a-button>
        <a-button
          type="primary"
          @click="submitHandle"
          :loading="submitLoading"
          >{{ submitType == "add" ? "完成添加" : "完成编辑" }}</a-button
        >
      </a-space>
    </template>
  </a-modal>
</template>
<script>
import { defineComponent, ref, reactive, toRefs } from "vue";
import { Empty, message } from "ant-design-vue";
import request from "@/common/utils/request";
import draggable from "vuedraggable";
export default defineComponent({
  components: {
    draggable,
  },
  setup(props, context) {
    const state = reactive({
      visible: false,
      formState: {
        sort_title: "",
      },
      detailInfo: {}, //商品详情
      productList: [],
      submitType: "",
      submitLoading: false,
    });
    // 打开弹窗
    const showModal = (info) => {
      state.visible = true;
      state.detailInfo = info.productDetail;
      state.formState.sort_title = info.productDetail.elastic_title;
      state.submitType = info.openType;
      state.productList = JSON.parse(JSON.stringify(info.productList));
    };
    // 关闭弹窗
    const close = (e) => {
      state.visible = false;
      formRef.value && formRef.value.resetFields();
    };
    const formRef = ref(null);
    //   提交表单
    const submitHandle = () => {
      formRef.value &&
        formRef.value
          .validate()
          .then(() => {
            // 新增
            if (state.submitType == "add") {
              const findIndex = state.productList?.findIndex(
                (ele) =>
                  ele.unique_product_id == state.detailInfo.unique_product_id
              );
              // 判断是否有重复添加
              if (findIndex == -1) {
                // 更新购物车
                let arrList = JSON.parse(JSON.stringify(state.productList));
                let filterAccountList = [];
                if (arrList.length > 0) {
                  filterAccountList = state.productList.filter(
                    (ele) => ele.id == state.detailInfo.id
                  );
                }
                arrList.push({
                  ...state.detailInfo,
                  elastic_title: state.formState.sort_title,
                });
                state.submitLoading = true;
                let paramsObj = {
                  raw_draft: arrList.filter(
                    (item) => item.id == state.detailInfo.id
                  ),
                  id: state.detailInfo.id,
                };
                if (filterAccountList.length > 0) {
                  paramsObj.draft_id = filterAccountList[0].draft_id;
                }
                request
                  .post(
                    "/work_ai",
                    "/org/platformAccount/douyin/draftUpdate",
                    paramsObj
                  )
                  .then((res) => {
                    state.productList.push({
                      ...state.detailInfo,
                      elastic_title: state.formState.sort_title,
                    });
                    state.productList[state.productList.length - 1].draft_id =
                      res.result.shop_draft_id;
                    message.success("添加成功");
                    context.emit("success", state.productList);
                    state.visible = false;
                    state.submitLoading = false;
                  })
                  .catch((err) => {
                    console.log(err);
                    state.visible = false;
                    state.submitLoading = false;
                  });
              } else {
                message.warning("重复添加商品");
              }
            } else if (state.submitType == "edit") {
              // 编辑
              let editIndex = state.productList.findIndex(
                (item) =>
                  item.unique_product_id == state.detailInfo.unique_product_id
              ); //获取编辑索引
              if (editIndex != -1) {
                let editList = JSON.parse(JSON.stringify(state.productList));
                editList[editIndex] = {
                  ...state.detailInfo,
                  elastic_title: state.formState.sort_title,
                };
                state.submitLoading = true;
                request
                  .post("/work_ai", "/org/platformAccount/douyin/draftUpdate", {
                    raw_draft: editList.filter(
                      (item) => item.id == state.detailInfo.id
                    ),
                    id: state.detailInfo.id,
                    draft_id: state.detailInfo.draft_id,
                  })
                  .then((res) => {
                    state.productList[editIndex] = {
                      ...state.detailInfo,
                      elastic_title: state.formState.sort_title,
                    };
                    message.success("修改成功");
                    context.emit("success", state.productList);
                    state.visible = false;
                    state.submitLoading = false;
                  })
                  .catch((err) => {
                    console.log(err);
                    state.visible = false;
                    state.submitLoading = false;
                  });
              }
            }
          })
          .catch((err) => {
            console.log(err);
          });
    };
    return {
      ...toRefs(state),
      showModal,
      close,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      formRef,
      submitHandle,
    };
  },
});
</script>
<style lang="less" scoped>
.content {
  .title {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .lf {
      font-weight: 600;
    }
    .rg {
      color: #a7a8a9;
    }
  }
  .productImg-list {
    margin-top: 10px;
    display: flex;
    width: 100%;
    overflow-x: auto;
    padding-bottom: 10px;
    .productImg-item {
      min-width: 100px;
      max-width: 100px;
      height: 100px;
      margin-right: 12px;
      background-color: #d7d7d7;
      img {
        width: 100px;
        height: 100px;
      }
    }
  }
  .original_title {
    margin-top: 5px;
    color: rgba(38, 38, 38, 0.8);
  }
}
</style>
